<template>
  <div class="app-container">
    <div style="background-color: white;padding: 10px 10px 10px 10px">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="88px">
        <el-form-item label="上传人" prop="createBy">
          <el-input
            v-model="queryParams.createBy"
            placeholder="上传人名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="学校名称" prop="schoolName" v-if="false">
          <el-input
            v-model="queryParams.schoolName"
            placeholder="上传学校名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <!--          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>-->
        </el-form-item>
      </el-form>
    </div>
    <div style="background-color: white;margin-top: 10px;padding: 20px">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd(false)"
            v-hasPermi="['patrol:dailyform:add']"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5" v-if="dailytype != 9">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="handleDownload()"
            v-hasPermi="['patrol:type:query']"
          >下载模版
          </el-button>
        </el-col>
        <el-col :span="1.5" v-if="dailytype != 9">
          <el-button
            type="primary"
            icon="el-icon-refresh"
            size="mini"
            @click="handleAdd(true)"
            v-hasPermi="['patrol:type:edit']"
          >上传/更新模版
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            size="mini"
            @click="function(){
              notFilledIn=true;
            }"
            v-if="!this.$auth.hasPermi('patrol:dailyform:edit')"
          >选择日期查看未填报学校
          </el-button>
        </el-col>
      </el-row>

      <el-table style="border-right: 1px solid #E3E3E3;border-left: 1px solid #E3E3E3" v-loading="loading"
                :data="dailyformList" :header-cell-style="{background:'#E3E3E3'}"
                @selection-change="handleSelectionChange">
        <el-table-column label="学校名称" align="center" prop="schoolName"/>
        <el-table-column label="上传时间" align="center" prop="createTime">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="上传人" align="center" prop="createBy">
          <template slot-scope="scope">
            <span>***</span>
          </template>
        </el-table-column>
        <el-table-column label="文件" align="center" prop="file">
          <template slot-scope="scope">
            <el-link type="primary"
                     :underline="false"
                     @click="handleDownload(scope.row.file)">
              {{
                scope.row.file.toString().substring(scope.row.file.toString().lastIndexOf('_') + 1)
              }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column v-if="this.$auth.hasPermi('patrol:dailyform:edit')" label="操作" align="center"
                         class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['patrol:dailyform:edit']"
            >修改
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['patrol:dailyform:edit']"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改常用表单文件对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item v-if="!type" label="上传日期">
            <el-date-picker
              v-model="createTime"
              type="date"
              placeholder=""
              :disabled="true"
            />
          </el-form-item>
          <el-form-item label="文件">
            <el-upload
              ref="upload"
              :limit="1"
              accept=".doc,.docx"
              :action="upload.url"
              :headers="upload.headers"
              :file-list="upload.fileList"
              :on-progress="handleFileUploadProgress"
              :before-upload="uploadInspect"
              :on-success="handleFileSuccess"
              :auto-upload="true">
              <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
              <div slot="tip" class="el-upload__tip">支持.doc/.docx格式文件上传</div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
      <el-dialog title="查看未填报学校" :visible.sync="notFilledIn" width="80%" append-to-body>
        <div>选择查看的日期：
          <el-date-picker
            v-model="notFilledInDate"
            type="date"
            placeholder="选择日期"
            @change="getnotFilledInData"
            value-format="yyyy-MM-dd HH:mm:ss"
            :size="size"
          />
          <span style="margin-left: 20px" v-if="notFilledInData.length>0">一共有{{
              notFilledInData.length
            }}所学校未填报当日表格</span>
        </div>
        <el-row :gutter="24" v-if="notFilledInData.length>0">
          <el-col v-for="itme in notFilledInData" :span="6">
            <div class="grid-content ep-bg-purple" style="margin: 10px auto"/>
            {{ itme.schoolName }}
          </el-col>
        </el-row>
        <el-row v-else :gutter="24">
          <div style="height: 200px;width: 100%;text-align: center">暂无数据</div>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  listDailyformtype,
  getDailyformtype,
  delDailyformtype,
  addDailyformtype,
  updateDailyformtype,
  exportDailyformtype,
  listDailyform,
  getDailyform,
  delDailyform,
  addDailyform,
  updateDailyform,
  exportDailyform,
  getnotFilledIn
} from "@/api/patrol/daily";
import {getToken} from "@/utils/auth";

export default {
  name: "daily",
  data() {
    return {
      size: 'large',
      notFilledIn: false,
      notFilledInDate: null,
      notFilledInData: [],
      temporaryFiles: null,
      // 遮罩层
      loading: true,
      //是否添加模版
      type: false,
      //模版id，页面url最后数字
      dailytype: 1,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 常用表单文件表格数据
      dailyformList: [],
      // 弹出层标题
      title: "",
      //模版对象
      stencil: {},
      // 是否显示弹出层
      open: false,
      createTime: new Date(),
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
        // 上传的文件列表
        fileList: []
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        createBy: null,
        schoolName: null,
      },
      // 表单参数
      form: {
        file: null
      },
      // 表单校验
      rules: {
        file: [
          {required: true, message: "文件路径不能为空", trigger: "blur"}
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getnotFilledInData(v) {
      console.log(this.notFilledInDate)
      if (this.notFilledInDate == null)
        return;
      getnotFilledIn({formDailyTypeId: this.dailytype, createTime: this.notFilledInDate})
        .then(value => {
          this.notFilledInData = value.data;
        })
    },
    /** 查询常用表单文件列表 */
    getList() {
      this.loading = true;
      // var dailytype = window.location.pathname.split('/');
      // this.dailytype = dailytype[dailytype.length - 1];
      let schoolInfo = this.$route.query.schoolInfo;
      if (schoolInfo) {
        // this.queryParams.schoolId = schoolInfo.id;
        console.log(schoolInfo)
        this.queryParams.schoolName=schoolInfo.name
      }
      this.dailytype=this.$route.query.daily

      getDailyformtype(this.dailytype).then(data => {
        console.log(data['data'])
        this.title = data.data['name']
        this.stencil = data.data;
        this.queryParams.formDailyTypeId = this.dailytype;
        listDailyform(this.queryParams).then(response => {
          response.rows.forEach(res=>{
            // 获取前两个字符和后两个字符
            const end = res.schoolName.slice(-2);
            // 计算中间部分长度并替换为*
            const middleLength = res.schoolName.length - 2;
            const middle = '*'.repeat(middleLength);
            res.schoolName = middle + end;
          })
          this.dailyformList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        formDailyTypeId: null,
        file: null,
        deleteflag: null,
        createTime: null,
        createBy: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd(type) {
      this.temporaryFiles = null;
      this.reset();
      this.type = type;
      this.form = {};
      if (type) {
        this.title = "上传模板文件";
        if (this.stencil.file != null && this.stencil.file !== "") {
          this.upload.fileList = [{
            name: this.stencil.file.split('_')[1],
            url: process.env.VUE_APP_BASE_API + this.stencil.file
          }];
        }
      } else {
        this.title = this.stencil.name;
        this.upload.fileList = [];
      }
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.temporaryFiles = null;
      console.log(row)
      this.type = false;
      this.upload.fileList = [{
        name: row.file.split('_')[1],
        url: process.env.VUE_APP_BASE_API + row.file
      }]
      this.title = "修改文件"
      this.form = row;
      this.open = true;
    },
    /** 下载模版*/
    handleDownload(filepath) {
      if (filepath == null)
        if (this.stencil.file == null || this.stencil.file === "") {
          this.$modal.alertError('没有模版文件，请联系管理员上传模版')
          return;
        } else {
          filepath = this.stencil.file
        }
      const a = document.createElement('a')
      a.setAttribute('target', '_blank')
      a.setAttribute('download', filepath == null ? this.title :
        filepath.toString().substring(filepath.toString().lastIndexOf('_') + 1));
      a.setAttribute('href', process.env.VUE_APP_BASE_API + filepath)
      a.click()
    },
    /** 提交按钮 */
    submitForm() {
      // this.$refs.upload.submit();
      if (this.temporaryFiles == null || this.temporaryFiles.toString().length < 1) {
        this.$message.error('请选择上传的文件或等待文件上传完成')
        return;
      }
      if (this.type) {
        this.stencil.file = this.temporaryFiles;
        this.$refs["form"].validate(valid => {
          if (valid) {
            updateDailyformtype(this.stencil).then(response => {
              this.msgSuccess("提交成功");
              this.$tab.refreshPage();
            });
          }
        });
      } else {
        this.form.file = this.temporaryFiles;
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.form.formDailyTypeId = this.dailytype
            if (this.form.id != null) {
              updateDailyform(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addDailyform(this.form).then(response => {
                this.msgSuccess("提交成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      console.log(row)
      this.$confirm('是否确认删除上传时间为"' + row.updateTime + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        row.deleteflag = 1;
        return updateDailyform(row);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
// 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
// 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.temporaryFiles = response.fileName;
      this.$message.success("文件上传成功，可以提交")
      console.log(response)
    },
    uploadInspect(file) {
      console.log(file.name.length)
      let isRightSize = file.name.length <= 100
      if (!isRightSize) {
        this.$message.error('文件名应小于100字符，请修改！')
      }
      return isRightSize
    }
  }
};
</script>

<style scoped>
.app-container {
  background-color: #edf1f2;
  padding: 10px;
  min-height: calc(100vh - 35px)
}

::v-deep.pagination-container .el-pagination {
  text-align: center;
  position: sticky;
}

::v-deep.el-form-item {
  margin-bottom: 0;
}
</style>
